﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CgManager : MonoBehaviour
{
    public GameObject CgImageUIPrefab;
    public ScrollRect CgScrollRect;
    public RawImage CgBigShow;
    byte CgState = Constants.Cg_Hide;
    private void Awake()
    {
        GameObject tempCgImage;     
        foreach (var item in GlobalData.CgDictionary.Values)
        {
            tempCgImage = Instantiate(CgImageUIPrefab);
            tempCgImage.transform.SetParent(CgScrollRect.content);
            tempCgImage.transform.localScale = Vector3.one; //重置缩放，否则分辨率改变会显示导致错位
            if (item.CanbeSeem)
            {
                tempCgImage.GetComponentInChildren<RawImage>().texture = item.Cg;
                tempCgImage.GetComponentInChildren<Button>().onClick.AddListener(delegate () { OnCgImageClick(item.Cg/*, tempCgImage.transform*/); });
            }
            else
                tempCgImage.GetComponentInChildren<RawImage>().texture = Texture2D.blackTexture;
        }
    }
    private void Update()
    {
        if (CgState == Constants.Cg_Shown && Input.GetMouseButtonDown(0))
        {
            StartCoroutine(HidCg());
        }
    }
    public void OnCgImageClick(Texture2D cg/*,Transform sender*/)
    {
        if (CgState == Constants.Cg_Hide)
        {
            CgBigShow.texture = cg;
            CgBigShow.gameObject.SetActive(true);
            //cgBigShow.transform.position = sender.position;
            StartCoroutine(ShowCg());
        }
    }
    IEnumerator ShowCg()
    {
        CgState = Constants.Cg_Showing;
        float t = 0f;
        Color c = Color.white;
        while (t < 0.5f)
        {
            t += Time.deltaTime;
            c.a = t * 2f;
            CgBigShow.color = c;
            yield return new WaitForEndOfFrame();
        }
        c.a = 1f;
        CgBigShow.color = c;
        CgState = Constants.Cg_Shown;
    }
    IEnumerator HidCg()
    {
        CgState = Constants.Cg_Hiding;
        float t = 0.5f;
        Color c = Color.white;
        while (t > 0f)
        {
            t -= Time.deltaTime;
            c.a = t * 2f;
            CgBigShow.color = c;
            yield return new WaitForEndOfFrame();
        }
        c.a = 0f;
        CgBigShow.color = c;
        CgBigShow.gameObject.SetActive(false);
        CgState = Constants.Cg_Hide;
    }
}
